﻿import tkinter as tk, tkinter.ttk as ttk, socket, select
import ui_data, mainlist, mainframe
class MainState(tk.Frame):
    """信息主窗口"""
    def __init__(self, parent:tk.PanedWindow, UI ) -> None:
        super().__init__(parent, background="#6666CC", height=30 )
        self.prev = tk.Button(self, text = "🡄", command= self.prev)
        self.prev.pack(side="left")
        self.next = tk.Button(self, text = "🡆", command= self.next)
        self.next.pack(side="left")
        self.UI = UI
        self.showing  = None
        pass
    
    def add(self, data:ui_data.AData):
        """返回新创建的控件"""
        return State(self, data)
        pass
    
    def remove(self, data:ui_data.AData):
        self.showing = None
        if(data.protocol.type == "RAW"):
            data.protocol.ms.destroy()
    
    def show(self, data:ui_data.AData):
        """显示对应的控件"""
        # print ("查找前：",self.pack_slaves())
        # print (self.pack_info())
        if(data.protocol.ms):
            for c in self.pack_slaves():
                if c._name.startswith("stateframe"):
                    c.pack_forget()
                    # print ("删除了：",self.pack_slaves())
                    break
        
            data.protocol.ms.pack(after = self.next, side = "right", expand = 1, anchor = "w")
            self.showing = data.channel.id
        # print ("添加了：",self.pack_slaves())
        pass
    
    def update(self, data:ui_data.AData):
        stateframe = "stateframe" + str(data.channel.id)
        for w in self.winfo_children():
            if w._name == stateframe:
                w.update(data)
                break
        pass
    
    def get_children(self, row = None)->tuple:
        l = []
        for c in self.UI.sml.mainlist.get_children(row):
            if(isinstance(self.UI.sml.mainlist.item(c,"text"), int)):
                l.append((c, self.UI.sml.mainlist.item(c,"text")))
                r = self.get_children(c)
                if(r):
                    l.extend(r)
        return tuple(l)
        
    def prev(self):
        """显示前一个通道"""
        # 查找下一前一个通道
        children = self.get_children()
        if(not children):
            return
        if(self.showing == None):
            for id,data in self.UI.ADATA.items():
                if(id == children[-1][1] ): # 最后一个
                    self.UI.show( data )
                    break
            return
        i = 0
        last_child = len(children)-1
        for child in children:
            if(child[1] == self.showing):
                if(i == 0):
                    i = last_child
                else:
                    i -= 1
                # 查找对应的 ml
                for id, data in self.UI.ADATA.items():
                    if(id == children[i][1] ):
                        self.UI.show(data)
                        break
                break
            i += 1
        pass
    
    def next(self):
        """显示后一个通道"""
        children = self.get_children()
        if(not children):
            return
        if(self.showing == None):
            for id,data in self.UI.ADATA.items():
                if(id == children[0][1] ): # 最前一个
                    self.UI.show( data )
                    break
            return
        i = 0
        last_child = len(children)-1
        for child in children:
            if(child[1] == self.showing):
                if(i == last_child):
                    i = 0
                else:
                    i += 1
                # 查找对应的 ml
                for id, data in self.UI.ADATA.items():
                    if(id == children[i][1] ):
                        self.UI.show(data)
                        break
                break
            i += 1

class State(tk.Frame):
    def __init__(self, master, data:ui_data.AData):
        super().__init__(master,name= "stateframe" + str(data.channel.id), background="#0066CC")
        self.ID = data.channel.id
        # state.pack(after = self.next, side = "right", expand = 1, anchor = "w")
        self.pState = tk.Label(self, name="state", text = data.channel.status[0], background = data.channel.status[1])
        self.pState.grid(column = 0, row = 0)
        self.pInfo = tk.Label(self, name="info", text =data.channel.info + " / " + data.protocol.info )
        self.pInfo.grid(column = 1, row = 0)
  
    def update(self, data:dict) -> None:
        self.pState.configure(text = data.channel.status[0], background = data.channel.status[1])
        self.pInfo.configure(text = data.channel.info + " / " + data.protocol.info )
                
    def show(self) ->None:
        for c in self.master.pack_slaves():
            if c._name.startswith("stateframe"):
                c.pack_forget()
                # print ("删除了：",self.pack_slaves())
                break
        self.pack(after = self.next, side = "right", expand = 1, anchor = "w")
        self.master.showing = self